using System;
using System.Collections.Generic;
using System.Text;

namespace MimeCloud.Foundations.Extensions
{
    public static class IEnumerable
    {
        /// <summary>
        /// For each IEnumerable Action Extension.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items">The items.</param>
        /// <param name="action">The action.</param>
        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
        {
            foreach (var item in items) action(item);
        }
    
        public static string ToCsvString<T>(this IEnumerable<T> items)
        {
            return ToCsvString(items, ", ");
        }
        
        public static string ToCsvString<T>(this IEnumerable<T> items, string delimiter)
        {
            return ToCsvString(items, delimiter, null);
        }

        /// <summary>
        /// Concatenate a list of items into a delimiter separated string,
        /// using .ToString() on each.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="delimiter"></param>
        /// <param name="itemSurroundingCharacter">A character to surround the values with eg. single quote => "'abc', 'def'"</param>
        /// <returns></returns>
        public static string ToCsvString<T>(this IEnumerable<T> items, string delimiter, char? itemSurroundingCharacter)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (T item in items)
            {
                if (stringBuilder.Length != 0)
                {
                    stringBuilder.Append(delimiter);
                }
                stringBuilder.Append(itemSurroundingCharacter.HasValue ?
                    String.Concat(itemSurroundingCharacter, item, itemSurroundingCharacter) :
                    item.ToString());                
            }
            return stringBuilder.ToString();
        }
    
    }
}